package ru.amse.vlassiev.view;

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class Graph extends JPanel implements IView {
	
	private final String myName;
	private java.util.List<DataPoint> myValue;
	private final int POINTSNUMBER = 100;
	private final int CAPTURESNUMBER = 10;
	private final double CAPTURE = 0.95;
	private final double ZERO = 0.90;
	private final long MAXVALUE = 2500000l;
	
	private class DataPoint {
		private long myValue;
		private String myCapture;
		
		public DataPoint(long value, String capture) {
			myValue = value;
			myCapture = capture;
		}
		
		public long getValue() {
			return myValue;
		}
		
		public String getCapture() {
			return myCapture;
		}
	}
	
	
	public Graph(String name) {
		super();
		myName = name;
		myValue = new ArrayList<DataPoint>();
	}

	public void update(String timestamp, long value) {
		myValue.add(new DataPoint(value, timestamp));
		this.repaint();
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		double width = this.getBounds().getWidth();
		double height = this.getBounds().getHeight();
		double step = width / (POINTSNUMBER + 2);
		double vertScale = height / MAXVALUE;
		final double yZero = height * ZERO;
		final double yCapture = height * CAPTURE;
		double x0 = step;
		double y0 = -1;
		double x = 0;
		double y = yZero;
		int dataLength = myValue.size();
		for (int i = dataLength > POINTSNUMBER ? dataLength - POINTSNUMBER : 0; i < dataLength; ++i) {
			DataPoint point = myValue.get(i);
			x += step;
			y = yZero - vertScale * point.getValue();
			if (y0 < 0) y0 = y;
			g.drawLine((int) x0, (int) y0, (int) x, (int) y);
			if (i % ((int) (POINTSNUMBER / CAPTURESNUMBER)) == 0) {
				g.drawChars(point.getCapture().toCharArray() , 0, point.getCapture().length(), (int) (0.75 * x + x0 * 0.25), (int) yCapture);
			}
			x0 = x;
			y0 = y;
		}
	}

}
